/**
 * 
 */
package info.niwota.commons;

import java.util.Comparator;

/**
 * @author qiangli
 *
 */
public class FileItemComparator implements Comparator<FileItem> {
	private int sort = 0;
	private int dir = 1;
	
	public FileItemComparator() {
	}
	
	public FileItemComparator(String sort, boolean asc) {
		this.sort = convert(sort);
		this.dir = (asc ? 1 : -1);
	}

	private int convert(String s) {
		if (s == null) {
			return 0;
		}
		s = s.toLowerCase();
		if (s.equals("name")) {
			return 0;
		}
		if (s.equals("type")) {
			return 1;
		}
		if (s.equals("size")) {
			return 2;
		}
		if (s.equals("date")) {
			return 3;
		}
		return 0;
	}

	public int compare(FileItem f1, FileItem f2) {
		if (f1 == null) {
			return -dir;
		}
		if (f2 == null) {
			return dir;
		}
		switch(sort) {
		case 1:
			if (f1.type == null) {
				return -dir; 
			}
			if (f2.type == null) {
				return dir;
			}
			return f1.type.compareTo(f2.type) * dir;
		case 2:
			return (int) (f1.size - f2.size) * dir;
		case 3:
			return (int) (f1.date - f2.date) * dir;
		case 0:
		default:
		}
		if (f1.name == null) {
			return -dir; 
		}
		if (f2.name == null) {
			return dir;
		}
		return f1.name.compareTo(f2.name) * dir;
	}
}
